import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import vueJsx from "@vitejs/plugin-vue-jsx";
import { fileURLToPath, URL } from "node:url";
import path from "node:path";
import viteCompression from "vite-plugin-compression";
import vueDevTools from "vite-plugin-vue-devtools";

// https://vite.dev/config/
export default ({ mode }: { mode: string }) => {
  const root = process.cwd();
  const env = loadEnv(mode, root);
  const { VITE_VERSION, VITE_PORT, VITE_BASE_URL, VITE_API_URL } = env;

  console.log(`⚙️  MODE = ${mode}`);
  console.log(`🌐 BASE_URL = ${VITE_BASE_URL}`);
  console.log(`🔌 VITE_PORT = ${VITE_PORT}`);
  console.log(`🔗 API_URL = ${VITE_API_URL}`);
  console.log(`📦 VERSION = ${VITE_VERSION}`);

  return defineConfig({
    define: {
      __APP_VERSION__: JSON.stringify(VITE_VERSION),
    },
    base: VITE_BASE_URL,
    server: {
      port: parseInt(VITE_PORT),
      proxy: {
        "/api": {
          target: VITE_API_URL,
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, ""),
        },
      },
      host: true,
    },
    // 路径别名
    resolve: {
      alias: {
        "@": fileURLToPath(new URL("./src", import.meta.url)),
        "@components": resolvePath("src/components"),
        "@views": resolvePath("src/views"),
        "@imgs": resolvePath("src/assets/images"),
        "@svgs": resolvePath("src/assets/svgs"),
        "@logos": resolvePath("src/assets/logo"),
        "@icons": resolvePath("src/assets/icons"),
        "@utils": resolvePath("src/utils"),
        "@stores": resolvePath("src/store"),
        "@plugins": resolvePath("src/plugins"),
        "@styles": resolvePath("src/assets/styles"),
      },
    },
    build: {
      target: "es2015",
      outDir: "dist",
      chunkSizeWarningLimit: 2000,
      minify: "terser",
      terserOptions: {
        compress: {
          drop_console: true, // 生产环境去除 console
          drop_debugger: true, // 生产环境去除 debugger
          pure_funcs: [
            "console.log",
            "console.info",
            "console.debug",
            "console.warn",
          ],
        },
      },
      rollupOptions: {
        output: {
          manualChunks: {
            // 将Vue相关库打包到vendor chunk
            vendor: ["vue", "vue-router", "pinia"],
            // 将ElementPlus打包到单独的chunk
            elementPlus: ["element-plus"],
            // 将图标库打包到单独的chunk
            icons: ["@icon-park/vue-next"],
            // 将工具库打包到单独的chunk
            utils: ["dayjs", "axios", "js-cookie"],
          },
          // 优化chunk文件名
          chunkFileNames: (chunkInfo) => {
            const facadeModuleId = chunkInfo.facadeModuleId
              ? chunkInfo.facadeModuleId.split("/").pop()
              : "chunk";
            return `js/[name]-[hash].js`;
          },
          entryFileNames: "js/[name]-[hash].js",
          assetFileNames: (assetInfo) => {
            const fileName = assetInfo.name || 'asset';
            const info = fileName.split(".");
            const ext = info[info.length - 1];
            if (/\.(css)$/.test(fileName)) {
              return `css/[name]-[hash].${ext}`;
            }
            if (/\.(png|jpe?g|gif|svg|webp|ico)$/.test(fileName)) {
              return `img/[name]-[hash].${ext}`;
            }
            if (/\.(woff2?|eot|ttf|otf)$/.test(fileName)) {
              return `fonts/[name]-[hash].${ext}`;
            }
            return `assets/[name]-[hash].${ext}`;
          },
        },
      },
      dynamicImportVarsOptions: {
        warnOnError: true,
        exclude: [],
        include: ["src/views/**/*.vue"],
      },
      // 启用CSS代码分割
      cssCodeSplit: true,
      // 启用源码映射（开发环境）
      sourcemap: mode === "development",
    },
    // 优化依赖预构建
    optimizeDeps: {
      include: [
        "vue",
        "vue-router",
        "pinia",
        "dayjs",
        "axios",
        "js-cookie",
        "@icon-park/vue-next/es/all",
      ],
    },
    plugins: [
      vue(),
      vueJsx(),
      // 压缩
      viteCompression({
        verbose: true, // 是否在控制台输出压缩结果
        disable: false, // 是否禁用
        algorithm: "gzip", // 压缩算法,可选 [ 'gzip' , 'brotliCompress' ,'deflate' , 'deflateRaw']
        ext: ".gz", // 压缩后的文件名后缀
        threshold: 10240, // 只有大小大于该值的资源会被处理 10240B = 10KB
        deleteOriginFile: false, // 压缩后是否删除原文件
      }),
      // 添加brotli压缩
      viteCompression({
        algorithm: "brotliCompress",
        ext: ".br",
        threshold: 10240,
        deleteOriginFile: false,
      }),
      vueDevTools(),
    ],
  });
};

function resolvePath(paths: string) {
  return path.resolve(process.cwd(), paths);
}
